﻿using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore.Storage;
using Process.API.Application.Command.Action.ProductionProcess;
using Process.ErrorCode;
using Process.Infrastructure.Implement;
using Process.Domain;
using System.Linq;

namespace Process.API.Application.Handler.Action.ProductionProcess
{
    public class AddProductionProcessTableHandler : IRequestHandler<AddProductionProcessTableCommand ,APIResult<int>>
    {
        DatabaseContext Db;
        IMapper mapper;

        public AddProductionProcessTableHandler(DatabaseContext db, IMapper mapper)
        {
            Db = db;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(AddProductionProcessTableCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            if (request.Items == null || request.Items.Count == 0)
            {
                result.Code = APIEnum.Fail;
                result.Message = "未提供需要添加的工序记录";
                result.Data = 0;
                return await Task.FromResult(result);
            }

            var entities = request.Items.Select(x => new ProductionProcessTable
            {
                ProcessNumber = x.ProcessNumber,
                ProductionOrdersId = x.ProductionOrdersId,
                ProcessId = x.ProcessId
            }).ToList();

            var affected = await Db.SqlSugar.Insertable(entities).ExecuteCommandAsync();

            result.Code = APIEnum.Ok;
            result.Message = "工序记录批量添加成功";
            result.Data = affected;
            return await Task.FromResult(result);
        }
    }
}
